<!-- 年度账单 -->
<template>
    <div class="box">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-overlay">
            <div class="loading-spinner"></div>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="error" class="error-message">
            {{ error }}
            <button @click="fetchBills" class="retry-btn">重试</button>
        </div>

        <div class="top_banner">
            <div class="top_one">
                <div class="back" @click="$router.back()">
                    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M25 5L10 20L25 35" stroke="white" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <div class="top_font">
                    年度账单
                </div>
                <div class="top_filter" @click="openFilter">
                    {{ selectedYear }}年
                    <svgIcon iconName="icon-xialacaidan" font-size="40px"></svgIcon>
                </div>
            </div>
            <div class="top_two">
                <div>
                    支出
                    <p>{{ totalExpense.toFixed(2) }}</p>
                </div>
                <div>
                    收入
                    <p>{{ totalIncome.toFixed(2) }}</p>
                </div>
                <div>
                    余额
                    <p>{{ totalBalance.toFixed(2) }}</p>
                </div>
            </div>
        </div>
        <div class="content">
            <div class="cont_title">
                <div>月份</div>
                <div>支出</div>
                <div>收入</div>
                <div>余额</div>
            </div>
            <div v-for="month in monthlyBills" :key="month.month" class="cont_item">
                <div>
                    {{ month.month }}月
                </div>
                <div>
                    {{ month.expense.toFixed(2) }}
                </div>
                <div>
                    {{ month.income.toFixed(2) }}
                </div>
                <div>
                    {{ month.balance.toFixed(2) }}
                </div>
            </div>
        </div>
    </div>

    <!-- 年份选择弹窗 -->
    <van-popup v-model:show="showFilter" position="bottom" round :style="{ height: '30%' }">
        <div class="filter-popup">
            <div class="filter-header">
                <div class="cancel" @click="showFilter = false">取消</div>
                <div class="title">选择年份</div>
                <div class="confirm" @click="confirmFilter">确定</div>
            </div>
            <div class="year-picker">
                <van-picker
                    :columns="yearColumns"
                    @change="onYearChange"
                    :default-index="yearDefaultIndex"
                    :show-toolbar="false"
                />
            </div>
        </div>
    </van-popup>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import request from '../utils/request';
import { Popup, Picker, Dialog } from 'vant';
import { showToast } from 'vant';

// 账单数据
const bills = ref([]);
const loading = ref(false);
const error = ref('');

// 从本地存储读取预算值，如果没有则默认为0.00
const yusuan = ref(parseFloat(localStorage.getItem('yusuan')) || 0.00);

// 筛选相关状态
const showFilter = ref(false);
const selectedYear = ref(new Date().getFullYear());
const tempSelectedYear = ref(new Date().getFullYear());
const yearDefaultIndex = ref(0);

// 年份列表
const yearColumns = computed(() => {
    const currentYear = new Date().getFullYear();
    return Array.from({length: currentYear - 2019 + 1}, (_, i) => ({
        text: `${2019 + i}年`,
        value: 2019 + i
    }));
});

// 年份选择变化
const onYearChange = (value) => {
    tempSelectedYear.value = value.selectedValues[0];
    yearDefaultIndex.value = value.selectedIndexes[0];
};

// 确认筛选
const confirmFilter = () => {
    selectedYear.value = tempSelectedYear.value;
    showFilter.value = false;
};

// 打开筛选弹窗
const openFilter = () => {
    tempSelectedYear.value = selectedYear.value;
    showFilter.value = true;
};

// 检查登录状态
const checkLogin = () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    if (!userInfo.isLogin) {
        error.value = '请先登录';
        bills.value = [];
        return false;
    }
    return true;
};

// 获取账单数据
const fetchBills = async () => {
    if (!checkLogin()) {
        return;
    }

    loading.value = true;
    error.value = '';
    
    try {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        const response = await request.get('/api/category/categories', null, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${userInfo.token}`
            }
        });
        
        if (Array.isArray(response.data)) {
            bills.value = response.data.flatMap(item => {
                if (!Array.isArray(item.data)) {
                    return [];
                }
                
                return item.data.map(dataItem => ({
                    id: item.id,
                    _id: dataItem._id,
                    order: item.order,
                    time: dataItem.time || new Date().toISOString(),
                    type: item.type || 'expense',
                    amount: dataItem.value || 0,
                    category: item.name || '未分类',
                    icon: item.icon || 'icon-jiangjin'
                }));
            });
        } else {
            bills.value = [];
            error.value = '数据格式不正确';
        }
    } catch (err) {
        console.error('获取账单数据失败:', err);
        if (err.response && err.response.status === 401) {
            error.value = '登录已过期，请重新登录';
            localStorage.removeItem('userInfo');
        } else if (err.code === 'ECONNABORTED') {
            error.value = '请求超时，请检查网络连接';
        } else if (err.message.includes('Network Error')) {
            error.value = '网络连接失败，请检查网络设置';
        } else {
            error.value = '获取账单数据失败，请稍后重试';
        }
        bills.value = [];
    } finally {
        loading.value = false;
        // 如果有错误，显示错误提示
        if (error.value) {
            showToast(error.value);
        }
    }
};

// 计算年度总支出
const totalExpense = computed(() => {
    try {
        const filteredBills = bills.value.filter(bill => {
            const billDate = new Date(bill.time);
            return billDate.getFullYear() === selectedYear.value && bill.type === 'expense';
        });
        
        return filteredBills.reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
    } catch (err) {
        console.error('计算年度总支出错误:', err);
        return 0;
    }
});

// 计算年度总收入
const totalIncome = computed(() => {
    try {
        const filteredBills = bills.value.filter(bill => {
            const billDate = new Date(bill.time);
            return billDate.getFullYear() === selectedYear.value && bill.type === 'income';
        });
        
        return filteredBills.reduce((sum, bill) => sum + (Number(bill.amount) || 0), 0);
    } catch (err) {
        console.error('计算年度总收入错误:', err);
        return 0;
    }
});

// 计算年度余额
const totalBalance = computed(() => {
    return totalIncome.value - totalExpense.value;
});

// 按月份分组账单数据
const monthlyBills = computed(() => {
    try {
        const months = Array.from({length: 12}, (_, i) => ({
            month: i + 1,
            expense: 0,
            income: 0,
            balance: 0
        }));
        
        bills.value.forEach(bill => {
            const billDate = new Date(bill.time);
            if (billDate.getFullYear() === selectedYear.value) {
                const month = billDate.getMonth();
                const amount = Number(bill.amount) || 0;
                
                if (bill.type === 'expense') {
                    months[month].expense += amount;
                } else {
                    months[month].income += amount;
                }
            }
        });
        
        // 计算每月余额
        months.forEach(month => {
            month.balance = month.income - month.expense;
        });
        
        return months;
    } catch (err) {
        console.error('月度账单分组处理错误:', err);
        return [];
    }
});

// 组件挂载时获取数据
onMounted(() => {
    fetchBills();
});
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    min-height: 100vh;
    .top_banner {
        width: 100%;
        height: 360px;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        font-size: 32px;
        color: #fff;
        .top_one {
            width: 100%;
            height: 100px;
            display: flex;
            padding: 0 30px;
            align-items: center;
            justify-content: space-between;
            .back {
                width: 120px;
            }   
        }
        .top_two {
            margin-top: 60px;
            width: 100%;
            height: 200px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            text-align: center;
            padding: 0 50px;
            div {
                p {
                    margin-top: 20px;
                }
            }
        }
    }
    .content {
        width: 100%;
        background-color: #fff;
        .cont_title {
            width: 100%;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: #f5f5f5;
            padding: 0 40px;
            div {
                font-size: 24px;
                color: gray;
            }
        }
        .cont_item {
            width: 100%;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 40px;
            border-bottom: 1px solid gray;
            div {
                font-size: 28px;
                color: #000;
            }
        }
    }
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #ff9bb7;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.error-message {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    z-index: 1000;
    
    .retry-btn {
        margin-top: 10px;
        padding: 8px 20px;
        background: #ff9bb7;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        
        &:hover {
            background: darken(#ff9bb7, 10%);
        }
    }
}

.filter-popup {
    height: 100%;
    display: flex;
    flex-direction: column;
    
    .filter-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20px;
        border-bottom: 1px solid #eee;
        
        .cancel, .confirm {
            font-size: 28px;
            color: #666;
            padding: 10px;
        }
        
        .confirm {
            color: #ff9bb7;
        }
        
        .title {
            font-size: 28px;
            color: #333;
        }
    }
    
    .year-picker {
        flex: 1;
        overflow: hidden;
    }
}

// 覆盖 vant 样式
:deep(.van-picker) {
    height: 100%;
    
    .van-picker-column {
        font-size: 42px;
    }
    
    .van-picker-column__item {
        color: #333;
        
        &--selected {
            color: #ff9bb7;
            font-weight: bold;
        }
    }
}

.yusuan_num {
    cursor: pointer;
    &:hover {
        opacity: 0.8;
    }
}
</style>